TOP

SQL keyword ORDER BY

YouLibreCalc for Excel logo

SQL ORDER BY Description

The keyword ORDER BY is used to sort the result set in ascending or descending order.

SQL ORDER BY sorts records in ascending order by default. To sort records in descending order, use the optional DESC keyword.


ORDER BY Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC

Demonstration database

The following is a sample from the "Customers" table of the "Northwind" database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.5021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.5023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SQL ORDER BY Example

The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" ("Country") column:

Run SQLSELECT * FROM Customers 
ORDER BY Country

ORDER BY DESC Example

The following SQL statement selects all customers from the "Customers" table, sorted in descending order (DESCending) by the "Country" ("Country") column:

Run SQLSELECT * FROM Customers 
ORDER BY Country DESC

ORDER BY Example of selecting multiple columns

The following SQL statement selects all customers from the Customers table, sorted by the columns "Country" and "CustomerName" ("Customer Name"). This means that it will order them by country, but if some rows have the same country, they will be ordered by customer name:

Run SQLSELECT * FROM Customers 
ORDER BY Country, CustomerName

ORDER BY Example of selecting multiple columns 2

The following SQL statement selects all customers from the "Customers" table, sorted in ascending order by the "Country" column and in descending order by the "CustomerName" column:

Run SQLSELECT * FROM Customers 
ORDER BY Country ASC, CustomerName DESC